package com.xuzz.study.redis.client;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.Socket;

/**
 * @author xuzz
 * @description
 * @date 2019-12-26 19:53
 */
public class Connection {
    private Socket socket;
    private String host;
    private Integer port;
    private OutputStream outputStream;
    private InputStream inputStream;

    public Connection(String host,Integer port)
    {
        this.host = host;
        this.port = port;
    }

    public void connect()
    {
        try
        {
            if(!isConnected())
            {
                socket=new Socket(host,port);
                outputStream=socket.getOutputStream();
                inputStream=socket.getInputStream();

                setPassword(this.outputStream);
            }
        }catch (IOException e) {
            e.printStackTrace();
        }
    }

    //判断是否已建立连接
    public boolean isConnected() {
        return socket != null && socket.isBound() && !socket.isClosed() && socket.isConnected()
                && !socket.isInputShutdown() && !socket.isOutputShutdown();
    }

    public Connection sendCommand(Protocol.Command cmd, byte[]... args)
    {
        try {
            this.connect();

            Protocol.sendCommand(this.outputStream,cmd,args);
            return this;
        } catch (Exception e) {
           throw e;
        }
    }

    //获取返回信息
    public String getStatusReply() {
        byte b[] = new byte[1024];
        try {
            socket.getInputStream().read(b);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return new String(b);
    }

    private static void setPassword(OutputStream outputStream)
    {

        StringBuffer stringBuffer=new StringBuffer();
        stringBuffer.append("*2\r\n");
        stringBuffer.append("$4\r\n");
        stringBuffer.append("AUTH\r\n");
        stringBuffer.append("$6\r\n");
        stringBuffer.append("123456\r\n");
        try
        {
            outputStream.write(stringBuffer.toString().getBytes());

        }
        catch(IOException ex)
        {

        }
    }

}
